package com.myx.servlet;

import com.myx.pojo.User;
import com.myx.service.user.UserService;
import com.myx.service.user.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "doRegisterServlet",value = "/doRegisterServlet")
public class doRegisterServlet extends HttpServlet {
    private UserService userService=new UserServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=UTF-8");

        //获取浏览器传递过来的请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String con_password = request.getParameter("con_password");
        String email = request.getParameter("email");

        //非空判断
        if (username==null||password==null||username.equals("")||password.equals("")){
            //临时空间，一次请求响应
            request.setAttribute("username_password_not_null","不能为空");
            //用请求转发，一次请求
            request.getRequestDispatcher("/pages/userCreate.jsp").forward(request,response);
        }

        //用户名唯一
        boolean is_exist = userService.isExistUsername(username);
        if (!is_exist){
            System.out.println("3");
            User user=new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setEmail(email);
            user.setUserType(1);
            boolean b= userService.addUser(user);

            if (b){
                System.out.println("4");
                request.getRequestDispatcher("/pages/registerSuccess.jsp").forward(request,response);
            }else {
                System.out.println("5");
                response.sendRedirect(request.getContextPath()+"/pages/registerFail.jsp");
            }

        }else {
            System.out.println("6");
            request.setAttribute("duplicate_username","重复");
            request.getRequestDispatcher("/pages/userCreate.jsp").forward(request,response);

        }


        //进行注册




    }
}
